<template>
  <div id="sider-menu">
    <a-menu
      v-model:selectedKeys="state.selectedKeys"
      mode="inline"
      :open-keys="state.openKeys"
      :items="items"
      @openChange="onOpenChange"
      @click="clickMenuItem"
    ></a-menu>
  </div>
</template>

<script lang="ts" setup>
import { useRouter } from 'vue-router'
import { reactive, watch } from 'vue'
import { ItemType } from 'ant-design-vue'
import { processUserMenus } from '@/router/menu'
import { useAuthUserStore } from '@/store/authUserStore'

const { userMenuItmes } = processUserMenus()
const items: ItemType[] = userMenuItmes

const authUserStore = useAuthUserStore()
const { activeMenu } = authUserStore

const state = reactive({
  rootSubmenuKeys: items.map((item) => item.key),
  openKeys: [activeMenu.openKey],
  selectedKeys: [activeMenu.selectedKey],
})
// 监听activeMenu的变化
watch(
  () => activeMenu,
  (newValue) => {
    state.openKeys = [newValue.openKey]
    state.selectedKeys = [newValue.selectedKey]
  },
  { deep: true }
)

const router = useRouter()
const clickMenuItem = (item: any) => {
  router.push({ name: item.key })
}

const onOpenChange = (openKeys: string[]) => {
  const latestOpenKey = openKeys.find((key) => !state.openKeys.includes(key))
  if (latestOpenKey && !state.rootSubmenuKeys.includes(latestOpenKey)) {
    state.openKeys = openKeys
  } else {
    state.openKeys = latestOpenKey ? [latestOpenKey] : []
  }
}
</script>

<style scoped></style>
